
/**
  * ******************************************************************************
  * @file           : CAN_receive.c/h
  * @brief          : CAN数据的接收和处理
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022  11/12 颜福兵.
  * All rights reserved.
  *
  **/

#include "CAN_receive.h"
#include "main.h"
#include "bsp_flash.h"

extern CAN_HandleTypeDef hcan;
chassis_power_t chassis_power;
extern uint32_t id_reading;
/**
 * @brief CAN滤波初始化
 * @param  no
 */
void can_filter_init(void) {
  CAN_FilterTypeDef can_filter_st;
  can_filter_st.FilterActivation = ENABLE;
  can_filter_st.FilterMode = CAN_FILTERMODE_IDMASK;
  can_filter_st.FilterScale = CAN_FILTERSCALE_32BIT;
  can_filter_st.FilterIdHigh = 0x0000;
  can_filter_st.FilterIdLow = 0x0000;
  can_filter_st.FilterMaskIdHigh = 0x0000;
  can_filter_st.FilterMaskIdLow = 0x0000;
  can_filter_st.FilterBank = 0;
  can_filter_st.FilterFIFOAssignment = CAN_RX_FIFO0;
  HAL_CAN_ConfigFilter(&hcan, &can_filter_st);
  HAL_CAN_Start(&hcan);
  HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING);
}

/**
  * @brief          hal库CAN回调函数,接收电机数据
  * @param[in]      hcan:CAN句柄指针
  * @retval         none
  */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef* hcan) {
  CAN_RxHeaderTypeDef rx_header;
  uint8_t rx_data[8];
  HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &rx_header, rx_data);
}

/**
 * @brief 发送数据
 * @param data 数据小于等于64位
 * @param id CAN的ID
 */
void can_send_message(uint16_t * data, uint32_t id) {
  uint32_t send_mail_box;
  static CAN_TxHeaderTypeDef  can_tx_message;
  static uint8_t              can_send_data[8];
  can_tx_message.StdId = id;
  can_tx_message.IDE = CAN_ID_STD;
  can_tx_message.RTR = CAN_RTR_DATA;
  can_tx_message.DLC = 0x08;
  can_send_data[0] = data[0] >> 8;
  can_send_data[1] = data[0];
  can_send_data[2] = data[1] >> 8;
  can_send_data[3] = data[1];
  can_send_data[4] = data[2] >> 8;
  can_send_data[5] = data[2];
  can_send_data[6] = data[3] >> 8;
  can_send_data[7] = data[3];
  HAL_CAN_AddTxMessage(&hcan, &can_tx_message, can_send_data, &send_mail_box);
}



void can_init(void) {
  can_filter_init();
  id_reading = Flash_ReadData(PARA_ADDR);
}

/**
 * @brief 超级电容发送数据
 * @param data 最大发送4个半字的数据
 */
 void supercap_send_message(uint16_t* data) {

  can_send_message(data,id_reading);
}

/**
  * @brief 返回底盘功率的指针
  * @param  no
  * @return point
  */
const chassis_power_t* get_chassis_power_point(void) {
  return &chassis_power;
}
 
